<template>
  <el-dialog width="550px" title="上传素材" v-model="dialogFormVisible" :draggable="true" @close="dialogClose">
    <div>
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogFormRules">
        <el-form-item prop="parentType" label="选择分组">
          <el-cascader :disabled="isdis" style="width:100%;" v-model="dialogForm.parentType" :options="parentTypeOptions"
            :props="parentProps" placeholder="请选择分组" />
        </el-form-item>
        <el-form-item prop="fileList" label="选择图片">
          <el-upload v-model:file-list="fileList" :multiple="true" :auto-upload="false" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-change="fileChange" :on-remove="handleRemove">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitHandle">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, ref, toRefs } from 'vue'
import api from '../api'
import { getStore, successDeal, warningDeal } from '@/utils/utils'
import axios from "axios"
export default {
  setup(props, context) {
    const dialogFormRef = ref(null)

    const imgUrlPass = (rule, value, callback) => {
      if (!state.fileList || state.fileList.length == 0) {
        callback(new Error('请选择需要上传的素材'))
      } else {
        callback()
      }
    }

    const state = reactive({
      loading: false,
      dialogFormVisible: false,
      dialogVisible: false,
      dialogImageUrl: null,
      dialogForm: {},
      parentTypeOptions: [],
      fileList: [],
      parentProps: {
        value: 'typeId',
        label: 'typeName',
        checkStrictly: true,
      },
      dialogFormRules: {
        parentType: [
          { required: true, message: '请选择分组', trigger: 'blur' },
        ],
        fileList: [
          { required: true, validator: imgUrlPass, trigger: 'blur' },
        ],
      },
    })

    function dialogShow(data = {}) {
      state.dialogForm = data
      getSucaiTree()
      state.dialogFormVisible = true
    }

    function getSucaiTree() {
      const obj = {

      }
      api.sucaiTypeLoadAll(obj).then(res => {
        if (res.code == '200') {
          state.parentTypeOptions = res.data.list
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handlePictureCardPreview(file) {
      state.dialogImageUrl = file.url
      state.dialogVisible = true
    }

    function dialogClose() {
      state.fileList = []
      dialogFormRef.value && dialogFormRef.value.resetFields()
    }

    function getParentType(parentTypeList) {
      return typeof parentTypeList == 'string' ? parentTypeList : parentTypeList[parentTypeList.length - 1]
    }

    function submitHandle() {
      if (state.loading) return
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          state.loading = true
          const token = window.localStorage.getItem("USER_TOKEN") || '';
          const uesrInfo = getStore("USER_INFO") || {};
          const Authorization = getStore("USER_AUTHOR") || {
            Authorization: `'','','',3,20,''`,
          };

          let param = new FormData()
          state.fileList && state.fileList.map(item => {
            param.append('file', item.raw, item.name)
          })
          param.append('typeId', getParentType(state.dialogForm.parentType) || null)

          let config = {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: token ? `Bearer ${token}` : '',
              username: uesrInfo.username || '',
              Authorization: Authorization.Authorization,
              platformHeadType: 'rcmsPlatform',
            }
          }
          axios.post('/ums/sucai/add', param, config).then(res => {
            if (res.data.code == '200') {
              successDeal('上传成功')
              context.emit('dialogClose')
              state.dialogFormVisible = false
            } else {
              warningDeal(res.msg)
            }
            state.loading = false
          }).catch(err => {
            state.loading = false
            console.log(err)
          })
        }
      })
    }

    function fileChange(e) {
      console.log(e)
    }

    return {
      ...toRefs(state),
      dialogFormRef,
      dialogShow,
      handlePictureCardPreview,
      dialogClose,
      submitHandle,
      fileChange,
    }
  }
}
</script>

<style>
</style>